import React, { useEffect, useRef, useState } from "react";
import axios from "axios";
import { Tag,Button } from "antd";
import { CheckCircleOutlined, CloseCircleOutlined } from "@ant-design/icons";
import { useModel } from "@umijs/max";

const FaceRecognition: React.FC = () => {
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const mediaStreamRef = useRef<MediaStream | null>(null);
  const [isRecognizing, setIsRecognizing] = useState<boolean>(false);
  const [recognitionResult, setRecognitionResult] = useState<any>(null);
  const { initialState } = useModel('@@initialState');
  // 获取摄像头视频流
  useEffect(() => {
    const getVideoStream = async () => {
      try {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
          throw new Error("getUserMedia is not supported in this browser.");
        }

        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        mediaStreamRef.current = stream;
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
        }
      } catch (err) {
        console.error("Error accessing webcam:", err);
        alert("摄像头无法访问，请检查权限或浏览器设置。");
      }
    };

    getVideoStream();

    // 清理函数，组件卸载时停止摄像头
    return () => {
      if (mediaStreamRef.current) {
        const tracks = mediaStreamRef.current.getTracks();
        tracks.forEach(track => track.stop());
        console.log("Media tracks stopped.");
      }
    };
  }, []);

  // 捕获图像并提交识别
  const handleCaptureAndSubmit = async () => {
    // 捕获图像
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");

    if (videoRef.current && context) {
      canvas.width = videoRef.current.videoWidth;
      canvas.height = videoRef.current.videoHeight;
      context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
      const img = canvas.toDataURL("image/jpeg");
        // 提交识别请求
    if (!img) {
      alert("请先捕获图像！");
      return;
    }

    setIsRecognizing(true);
    try {
      const formData = new FormData();
      formData.append("imageBase", img);  // 这里是捕获到的图像
      const token= localStorage.getItem("token") as string;
      // 替换成你的后端接口 URL
      const response = await axios.post("http://localhost:9001/face/vef", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          "Access-Control-Allow-Origin": "*",
          token
        },
        withCredentials : true,
        // cross: true,
      });

      setRecognitionResult(response.data);  // 处理后端返回的识别结果
    } catch (error) {
      console.error("人脸识别失败：", error);
      alert("识别请求失败，请稍后再试！");
    } finally {
      setIsRecognizing(false);
    }
    }

   
  };
 const IsOk: React.FC = () => {
       let dom = null;
       if (recognitionResult?.code === 200) {
          dom =  <Tag  icon={<CheckCircleOutlined />} color="success">打卡成功</Tag>;
       } else {
        dom =  <Tag icon={<CloseCircleOutlined />} color="error">打卡失败</Tag>;
       }
      
    return  <div  style={{margin:"20px 0px"}}>{recognitionResult && dom}</div>;
 }
  return (
    <div>
      <h1>人脸识别打卡</h1>
      <video ref={videoRef} autoPlay width="400" height="300" />
      <br />
      <Button  type="primary" onClick={handleCaptureAndSubmit} disabled={isRecognizing}>
        {isRecognizing ? "识别中..." : "点击打卡"}
      </Button>
      <br/>
      <IsOk/>
    </div>
  );
};

export default FaceRecognition;
